package com.bj.disc.util

import com.ai3d.rfid.base.app.App
import com.ai3d.rfid.common.event.ACache
import com.ai3d.rfid.common.event.EventMgs
import com.ai3d.rfid.common.event.JsonToBeanUtils
import com.ai3d.rfid.common.proxy.MMKVProxy
import com.bj.disc.database.EventReq
import java.io.File
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.UUID
import kotlin.random.Random

open class BaseGameUtil {
    fun getGameResult(games: List<Game>, level: Int, round: Int): Game? {
        return games.find { it.level == level && it.round == round }
    }

    //生成左边还是右边
    fun generateRandomNumber(): Int {
        val pr = (Math.random() * 100).toInt()
        return if (pr < 50) {
            0
        } else {
            1
        }
    }

    fun calculatePercentage(numerator: Int, denominator: Int): Int {
        println(numerator.toString()+"================="+denominator.toString()+"==========="+ (numerator.toDouble() / denominator.toDouble() * 100).toInt())
        return (numerator.toDouble() / denominator.toDouble() * 100).toInt()
    }

//    fun generateUniqueInteger(machineId: Long): Long {
//        var sequence = 0L
//        var lastTimestamp = -1L
//
//        fun waitUntilNextMillisecond(timestamp: Long): Long {
//            var newTimestamp = System.currentTimeMillis()
//            while (newTimestamp <= timestamp) {
//                newTimestamp = System.currentTimeMillis()
//            }
//            return newTimestamp
//        }
//
//        val timestamp = System.currentTimeMillis()
//
//        if (timestamp < lastTimestamp) {
//            throw Exception("Clock moved backwards. Rejecting requests until the clock moves forward again.")
//        }
//
//        if (timestamp == lastTimestamp) {
//            sequence = (sequence + 1) % 4096
//            if (sequence == 0L) {
//                lastTimestamp = waitUntilNextMillisecond(timestamp)
//            }
//        } else {
//            sequence = 0L
//        }
//
//        lastTimestamp = timestamp
//
//        val uniqueInteger = (timestamp shl 22) or (machineId shl 12) or sequence
//        return uniqueInteger
//    }

    //machineId 传入当前token+游戏类别（uot,oc,vf）
    fun generateUniquePositiveInteger(machineId: Long): String {
        return UUID.randomUUID().toString().replace("-","")
    }

    //全局唯一 每进入一个游戏类别生成一个  没有重置之前是不会改变的  生成以后 没有重置之前 请不要继续调用生成新的
    fun getGameSessionId(gameType: String): String {
        var userId = MMKVProxy.getString(MMKVProxy.KEY_USER_ID)//用户登录token
        return generateUniquePositiveInteger(stringToUniqueLong(userId + gameType + Random.nextInt(10000)))
    }

    //全局唯一 每进入一个level 没有重置之前是不会改变的 生成以后 没有重置之前 请不要继续调用生成新的
    fun getLevelSessionId(gameSessionId: String, level: String): String {
        return generateUniquePositiveInteger(stringToUniqueLong(gameSessionId + level + Random.nextInt(10000)))
    }

    //每一个round的id
    fun getSessionId(levelSessionId: String, round: String): String {
        return generateUniquePositiveInteger(stringToUniqueLong(levelSessionId + round + Random.nextInt(10000)))
    }

    fun stringToUniqueLong(str: String): Long {
        val messageDigest = MessageDigest.getInstance("SHA-256")
        val hashBytes = messageDigest.digest(str.toByteArray(StandardCharsets.UTF_8))

        // 只取前 8 个字节（64位）来构造长整型
        val uniqueLong = (hashBytes[0].toLong() and 0xFF) shl 56 or
                (hashBytes[1].toLong() and 0xFF) shl 48 or
                (hashBytes[2].toLong() and 0xFF) shl 40 or
                (hashBytes[3].toLong() and 0xFF) shl 32 or
                (hashBytes[4].toLong() and 0xFF) shl 24 or
                (hashBytes[5].toLong() and 0xFF) shl 16 or
                (hashBytes[6].toLong() and 0xFF) shl 8 or
                (hashBytes[7].toLong() and 0xFF)

        return uniqueLong
    }

    fun <T> MutableList<T>.shuffle(): MutableList<T> {
        val random = Random(42) // 设置固定的种子值，例如 42
        for (i in size - 1 downTo 1) {
            val j = random.nextInt(i + 1)
            val temp = this[i]
            this[i] = this[j]
            this[j] = temp
        }
        return this
    }

    fun getRandomSubset(originalList: MutableList<String>, subsetSize: Int): MutableList<String> {
        val resultList = mutableListOf<String>()
        originalList.shuffled().take(subsetSize).forEach {
            resultList.add(it)
        }
        return resultList
    }
    fun shuffledGameOcItem(originalList: ArrayList<GameOcItem>): ArrayList<GameOcItem> {
        val resultList = ArrayList<GameOcItem>()
        originalList.shuffled().take(originalList.size).forEach {
            resultList.add(it)
        }
        return resultList
    }
    fun getRandomFile(originalList: List<File>, subsetSize: Int): MutableList<File> {
//        var lastTheme=MMKVProxy.getString(MMKVProxy.LAST_THEME)
//        var storeList= lastTheme?.let {
//            JsonToBeanUtils.toBean<MutableList<String>>(
//                it
//            )
//        }
        val resultList = mutableListOf<File>()
//        if(null!=storeList&&storeList.size>0) {
//            originalList.removeAll(storeList)
//        }
        originalList.shuffled().take(subsetSize).forEach {
            resultList.add(it)
        }
        return resultList
    }


}